package xdu.lz.netty.g_handler.tcp_handler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @Author Badribbit
 * @create 2019/4/14 21:46
 */

/**
 * nett即可以做客户端也可以做服务端
 * 一对一交互
 */
public class MyServer {
    public static void main(String[] args) throws  Exception{
        //事件循环组
        //只是完成了一些参数的赋值，并没有开启什么东西。 参数是开启线程的个数，不传则是CPU核数*2
        long time1 = System.currentTimeMillis();
        EventLoopGroup bossGroup=new NioEventLoopGroup(1);
        EventLoopGroup workerGroup=new NioEventLoopGroup();
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class).  //初始化时候会被 加入到 ServerBootstrapAcceptor   Reactor中的Acceptor
                    childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {

                    //一个管道，里面有很多ChannelHandler，这些就像拦截器，可以做很多事
                    ChannelPipeline pipeline=ch.pipeline();

                    pipeline.addLast(new MyPersonDecoder());//入栈处理器
                    pipeline.addLast(new MyPersonEncoder()); //出栈处理器
                    pipeline.addLast(new MyServerHandler());//入栈处理器

                }
            });


            ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if( future.isSuccess()){

                        System.out.println("绑定完毕,用时"+(System.currentTimeMillis()-time1)+"ms");
                    }else{
                        System.out.println("绑定出现异常");
                        future.cause().printStackTrace();
                    }
                }
            });
            channelFuture.channel().closeFuture().sync();

        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
